import React, { useState, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'

export default function CarDetails() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const [selectedBrand, setSelectedBrand] = useState('')
  const [selectedSeries, setSelectedSeries] = useState('')
  const [selectedCarName, setSelectedCarName] = useState('')
  const [selectedCarPrice, setSelectedCarPrice] = useState('')
  const [selectedCarType, setSelectedCarType] = useState('')
  const [selectedCarCountry, setSelectedCarCountry] = useState('')
  const [selectedCarCategory, setSelectedCarCategory] = useState('')
  const [carModels, setCarModels] = useState([])
  const [loading, setLoading] = useState(true)

  console.log('CarDetails组件已加载')
  console.log('当前searchParams:', searchParams.toString())

  useEffect(() => {
    const brand = searchParams.get('brand')
    const series = searchParams.get('series')
    const name = searchParams.get('name')
    const price = searchParams.get('price')
    const type = searchParams.get('type')
    const country = searchParams.get('country')
    const category = searchParams.get('category')
    
    console.log('解析到的brand:', brand)
    console.log('解析到的series:', series)
    console.log('解析到的name:', name)
    console.log('解析到的price:', price)
    console.log('解析到的type:', type)
    console.log('解析到的country:', country)
    console.log('解析到的category:', category)
    
    if (brand) {
      setSelectedBrand(brand)
      setSelectedSeries(series || '')
      setSelectedCarName(name || '')
      setSelectedCarPrice(price || '')
      setSelectedCarType(type || '')
      setSelectedCarCountry(country || '')
      setSelectedCarCategory(category || '')
      
      // 模拟获取车型数据
      setTimeout(() => {
        const mockModels = generateCarModels(brand, series, name)
        setCarModels(mockModels)
        setLoading(false)
      }, 500)
    }
  }, [searchParams])

  const generateCarModels = (brand, series, carName) => {
    const models = []
    const basePrice = Math.floor(Math.random() * 500000) + 100000
    
    // 如果传入了具体的车型名称，优先显示该车型的详细信息
    if (carName) {
      models.push({
        id: 1,
        name: carName,
        price: `${(basePrice).toLocaleString()}元`,
        year: '2024年',
        mileage: '0km',
        fuelType: '汽油',
        transmission: '自动',
        engine: '2.0T',
        power: '150kW',
        image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=300&h=200&fit=crop',
        isMainModel: true
      })
    }
    
    // 生成其他相关车型
    for (let i = 1; i <= 15; i++) {
      models.push({
        id: i + 1,
        name: series ? `${series} ${i}款` : `${brand} 车型${i}`,
        price: `${(basePrice + i * 10000).toLocaleString()}元`,
        year: `${2020 + (i % 5)}年`,
        mileage: `${(i * 1000).toLocaleString()}km`,
        fuelType: ['汽油', '柴油', '电动', '混动'][i % 4],
        transmission: ['手动', '自动', 'CVT', '双离合'][i % 4],
        engine: `${1.5 + (i % 3) * 0.5}T`,
        power: `${100 + i * 10}kW`,
        image: 'https://images.unsplash.com/photo-1555215695-3004980ad54e?w=300&h=200&fit=crop'
      })
    }
    
    return models
  }

  const handleBack = () => {
    navigate('/main')
  }

  const handleModelClick = (model) => {
    // 这里可以导航到具体的车型详情页
    console.log('选择车型:', model)
    alert(`您选择了: ${model.name}`)
  }

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        fontSize: '18px',
        color: '#666'
      }}>
        加载中...
      </div>
    )
  }

  return (
    <div style={{
      minHeight: '100vh',
      backgroundColor: '#f5f5f5',
      padding: '0 16px'
    }}>
      {/* 头部 */}
      <div style={{
        backgroundColor: '#fff',
        padding: '16px',
        marginBottom: '12px',
        borderRadius: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          marginBottom: '12px'
        }}>
          <button
            onClick={handleBack}
            style={{
              border: 'none',
              background: 'none',
              fontSize: '20px',
              cursor: 'pointer',
              marginRight: '12px',
              color: '#666'
            }}
          >
            ← 返回
          </button>
          <h1 style={{
            margin: 0,
            fontSize: '20px',
            color: '#333'
          }}>
            {selectedCarName || `${selectedBrand} ${selectedSeries}`}
          </h1>
        </div>
        <div style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: '10px',
          marginBottom: '10px'
        }}>
          {selectedCarType && (
            <span style={{
              backgroundColor: selectedCarType === '新能源' ? '#4CAF50' : selectedCarType === '二手车' ? '#FF9800' : '#ff6b35',
              color: 'white',
              padding: '4px 8px',
              borderRadius: '4px',
              fontSize: '12px'
            }}>
              {selectedCarType}
            </span>
          )}
          {selectedCarCountry && (
            <span style={{
              backgroundColor: '#007bff',
              color: 'white',
              padding: '4px 8px',
              borderRadius: '4px',
              fontSize: '12px'
            }}>
              {selectedCarCountry}
            </span>
          )}
          {selectedCarCategory && (
            <span style={{
              backgroundColor: '#28a745',
              color: 'white',
              padding: '4px 8px',
              borderRadius: '4px',
              fontSize: '12px'
            }}>
              {selectedCarCategory}
            </span>
          )}
        </div>
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '10px'
        }}>
          <p style={{
            margin: 0,
            color: '#666',
            fontSize: '14px'
          }}>
            共找到 {carModels.length} 款车型
          </p>
          {selectedCarPrice && (
            <p style={{
              margin: 0,
              color: '#ff6b35',
              fontSize: '16px',
              fontWeight: 'bold'
            }}>
              {selectedCarPrice}万起
            </p>
          )}
        </div>
      </div>

      {/* 车型列表 */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
        gap: '12px'
      }}>
        {carModels.map((model) => (
          <div
            key={model.id}
            onClick={() => handleModelClick(model)}
            style={{
              backgroundColor: model.isMainModel ? '#fff8e1' : '#fff',
              borderRadius: '8px',
              padding: '16px',
              boxShadow: model.isMainModel ? '0 4px 12px rgba(255,193,7,0.2)' : '0 2px 8px rgba(0,0,0,0.1)',
              cursor: 'pointer',
              transition: 'transform 0.2s',
              border: model.isMainModel ? '2px solid #ffc107' : '1px solid #f0f0f0',
              ':hover': {
                transform: 'translateY(-2px)'
              }
            }}
            onMouseEnter={(e) => {
              e.target.style.transform = 'translateY(-2px)'
              e.target.style.boxShadow = model.isMainModel ? '0 6px 16px rgba(255,193,7,0.3)' : '0 4px 12px rgba(0,0,0,0.15)'
            }}
            onMouseLeave={(e) => {
              e.target.style.transform = 'translateY(0)'
              e.target.style.boxShadow = model.isMainModel ? '0 4px 12px rgba(255,193,7,0.2)' : '0 2px 8px rgba(0,0,0,0.1)'
            }}
          >
            <div style={{
              display: 'flex',
              alignItems: 'center',
              marginBottom: '12px'
            }}>
              <img
                src={model.image}
                alt={model.name}
                style={{
                  width: '80px',
                  height: '60px',
                  objectFit: 'cover',
                  borderRadius: '4px',
                  marginRight: '12px'
                }}
              />
              <div>
                <div style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  marginBottom: '4px'
                }}>
                  <h3 style={{
                    margin: 0,
                    fontSize: '16px',
                    color: '#333'
                  }}>
                    {model.name}
                  </h3>
                  {model.isMainModel && (
                    <span style={{
                      backgroundColor: '#ffc107',
                      color: '#333',
                      padding: '2px 6px',
                      borderRadius: '3px',
                      fontSize: '10px',
                      fontWeight: 'bold'
                    }}>
                      主推
                    </span>
                  )}
                </div>
                <p style={{
                  margin: 0,
                  fontSize: '18px',
                  color: '#e74c3c',
                  fontWeight: 'bold'
                }}>
                  {model.price}
                </p>
              </div>
            </div>
            
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(2, 1fr)',
              gap: '8px',
              fontSize: '12px',
              color: '#666'
            }}>
              <div>年份: {model.year}</div>
              <div>里程: {model.mileage}</div>
              <div>燃料: {model.fuelType}</div>
              <div>变速箱: {model.transmission}</div>
              <div>发动机: {model.engine}</div>
              <div>功率: {model.power}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
} 